package com.roc.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.roc.bean.BindMerOper;
import com.roc.bean.BindMerParams;
import com.roc.dao.IBaseDao;
import com.roc.dao.ISQLBaseDao;
import com.roc.dao.impl.SQLBaseDaoImpl;
import com.roc.newPage.IPageDao;
import com.roc.pojo.Operators;
import com.roc.service.BindMchtService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.SysLogType;

/**
 * 绑定商户
 * @author Administrator
 *
 */
@Service
public class BindMchtServiceImpl implements BindMchtService{
	
	private static Logger logger = Logger.getLogger(BindMchtServiceImpl.class);
	
	@Autowired
	private IPageDao pageDao;
	
	@Autowired
	private ISQLBaseDao sqlBaseDao;
	
	@Autowired
	private IBaseDao baseDao;

	/**
	 * 查询绑定商户数据
	 * @param params
	 * @param startRow
	 * @param maxRow
	 * @return
	 * @throws ServiceException
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@Override
	public List<Object> queryBindList(BindMerParams params,
			int startRow, int maxRow) throws ServiceException {
		List<Object> paramsList = new ArrayList<Object>();
		StringBuffer sb = new StringBuffer(" SELECT A.MCHT_CD,A.NAME_BUSI,A.NAME MERNAME,TI.INS_NAME,A.CONTACT_NAME, ")
				.append(" A.CONTACT_PHONENO,A.CERTIF,A.CERTIF_NO,A.BUSI_LICE_NO,A.REG_ADDR, ")
				.append(" A.STATUS,(SELECT TP.REAL_NAME FROM T_OPERATORS TP WHERE TP.ID = to_number(A.ORI_CHNL_DESC)) RKNAME, ")
				.append(" '' some1,'' some2,'' some3,D.NAME ACCOUNTNAME,D.ACCOUNT,D.BANK_NAME, ")
				.append(" D.BANK_CODE,NVL2((SELECT DISTINCT PROD_CD FROM TBL_MCHT_BIZ_DEAL t WHERE t.MCHT_CD = A.MCHT_CD ")
				.append(" AND t.PROD_CD = '1000'),'T1',''),NVL2((SELECT DISTINCT PROD_CD FROM TBL_MCHT_BIZ_DEAL t WHERE t.MCHT_CD = A.MCHT_CD ")
				.append(" AND t.PROD_CD = '1171'),'T0',''), A.GROUP_CD, A.NATION_CD, A.ISGROUP,A.APPL_DATE,TE.TERM_ID,TE.DEVICE_CD ")
				.append(" FROM TBL_MCHT_INF A,TBL_MCHT_BANKACCOUNT D, (SELECT T1.INS_ID_CD, T1.INS_NAME FROM TBL_INS_INF T1) TI, ")
				.append(" TBL_TERM_INF TE,APSTFR.TBL_ROUTE_MCHT_INF RO WHERE A.MCHT_CD = D.OWNER_CD ")
				.append(" AND A.BANK_BELONG_CD = TI.INS_ID_CD AND A.MCHT_CD = TE.MCHT_CD AND TE.MCHT_CD=RO.MCHT_CD AND TE.TERM_ID=RO.TERM_ID  AND A.STATUS = '01' AND TE.STATUS='01' ");
		
		String mchtCd = Constance.Null2EmptyTrim(params.getMchtCd());
		String nameBusi = Constance.Null2EmptyTrim(params.getNameBusi());
		String minDate = Constance.Null2EmptyTrim(params.getMinDate());
		String maxDate = Constance.Null2EmptyTrim(params.getMaxDate());
		String termId = Constance.Null2EmptyTrim(params.getTermId());
		
		
		paramsList.add(mchtCd);
		sb.append(" AND A.MCHT_CD=? ");

		if (!"".equals(nameBusi)) {
			sb.append(" AND A.NAME_BUSI LIKE '%"+nameBusi+"%' ");
		}

		if (!"".equals(termId)) {
			paramsList.add(termId);
			sb.append("AND TE.TERM_ID=? ");
		}
		
		if (!"".equals(minDate) && !"".equals(maxDate)) {
			paramsList.add(minDate);
			paramsList.add(maxDate);
			sb.append(" AND A.APPL_DATE >=? AND A.APPL_DATE <=? ");
       	    
		}
		
		sb.append(" ORDER BY A.REC_CRT_TS DESC ");
		
		List<Object> searchRsList=new ArrayList<Object>();
		
		try {
			searchRsList = pageDao.findAllByParams(sb.toString(), paramsList, startRow, maxRow);
			logger.info("查询到记录："+searchRsList.size()+"条");
			
		} catch (Exception e) {
			logger.error("查询绑定商户数据异常",e);
		}
		return searchRsList;
	}

	/**
	 * 查询绑定商户数量
	 * @param params
	 * @return
	 * @throws ServiceException
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@Override
	public int queryBindListCount(BindMerParams params) throws ServiceException {
		List<Object> paramsList = new ArrayList<Object>();
		StringBuffer sb = new StringBuffer(" SELECT COUNT(1) ")
			.append(" FROM TBL_MCHT_INF A,TBL_MCHT_BANKACCOUNT D, (SELECT T1.INS_ID_CD, T1.INS_NAME FROM TBL_INS_INF T1) TI, ")
			.append(" TBL_TERM_INF TE,APSTFR.TBL_ROUTE_MCHT_INF RO WHERE A.MCHT_CD = D.OWNER_CD ")
			.append(" AND A.BANK_BELONG_CD = TI.INS_ID_CD AND A.MCHT_CD = TE.MCHT_CD AND TE.MCHT_CD=RO.MCHT_CD AND TE.TERM_ID=RO.TERM_ID  AND A.STATUS = '01' AND TE.STATUS='01' ");

		String mchtCd = Constance.Null2EmptyTrim(params.getMchtCd());
		String nameBusi = Constance.Null2EmptyTrim(params.getNameBusi());
		String minDate = Constance.Null2EmptyTrim(params.getMinDate());
		String maxDate = Constance.Null2EmptyTrim(params.getMaxDate());
		String termId = Constance.Null2EmptyTrim(params.getTermId());
		
		
		paramsList.add(mchtCd);
		sb.append(" AND A.MCHT_CD=? ");
		
		if (!"".equals(nameBusi)) {
			sb.append(" AND A.NAME_BUSI LIKE '%"+nameBusi+"%' ");
		}
		
		if (!"".equals(termId)) {
			paramsList.add(termId);
			sb.append("AND TE.TERM_ID=? ");
		}
		
		if (!"".equals(minDate) && !"".equals(maxDate)) {
			paramsList.add(minDate);
			paramsList.add(maxDate);
			sb.append(" AND A.APPL_DATE >=? AND A.APPL_DATE <=? ");
			    
		}
	
		sb.append(" ORDER BY A.REC_CRT_TS DESC ");
		
		int rowCount = 0;
		try {
			rowCount = pageDao.countByParams(sb.toString(),paramsList);
			
		} catch (Exception e) {
			logger.error("绑定商户数量查询异常",e);
		}
		return rowCount;
	}

	@Transactional(rollbackFor = { ServiceException.class })
	@Override
	public Map<String, Object> bindMerchant(Operators logingMerchant,BindMerOper bindMerOper)
			throws ServiceException {
		Map<String,Object> resMap = new HashMap<String, Object>();
		resMap.put("flag", false);
		resMap.put("msg", "操作失败");
		List<Object> paramsList = new ArrayList<Object>();
		
		try {
			
			String beforeMchtCd = Constance.Null2EmptyTrim(bindMerOper.getBeforeMchtcd());
			String beforeTermId = Constance.Null2EmptyTrim(bindMerOper.getBeforeTermId());
			String bindMchtCd = Constance.Null2EmptyTrim(bindMerOper.getBindMchtCd());
			String bindTermId = Constance.Null2EmptyTrim(bindMerOper.getBindTermId());
			
			if("".equals(beforeMchtCd)){
				resMap.put("msg", "前端商户号为空");
				return resMap;
			}
			
			if("".equals(beforeTermId)){
				resMap.put("msg", "前端终端号为空");
				return resMap;
			}
			
			if("".equals(bindMchtCd)){
				resMap.put("msg", "后端商户号为空");
				return resMap;
			}
			
			if("".equals(bindTermId)){
				resMap.put("msg", "后端终端号为空");
				return resMap;
			}
			
			logger.info("操作员【"+logingMerchant.getAccountNo()+"】开始绑定商户【"+beforeMchtCd+"】终端【"+beforeTermId+"】和商户【"+bindMchtCd+"】终端【"+bindTermId+"】");
			
			String selectBindSql = "select count(1) from apstfr.tbl_mcht_bind_inf t where t.MCHT_CD=? and t.TERM_ID=?";
			Object selBindObj = sqlBaseDao.findObj(selectBindSql, new Object[]{beforeMchtCd,beforeTermId});
			int selBindCount = Integer.parseInt(String.valueOf(selBindObj));
			
			
			
			if(selBindCount>0){
				resMap.put("msg", "商户号【"+beforeMchtCd+"】终端号【"+beforeTermId+"】绑定记录已存在");
				return resMap;
			}
			
			String insertBindSql = "insert into apstfr.tbl_mcht_bind_inf (MCHT_CD, TERM_ID, MCHT_CD_CONV, TERM_ID_CONV, STATUS, REC_CRT_TS, REC_UPD_TS, REMARK1, REMARK2, REMARK3)"
					+"values (?, ?, ?, ?, '01', SYSDATE, '', '1', '', '')";
			paramsList.clear();
			paramsList.add(beforeMchtCd);
			paramsList.add(beforeTermId);
			paramsList.add(bindMchtCd);
			paramsList.add(bindTermId);
			int insertBindCount = sqlBaseDao.deleteBySql(insertBindSql, paramsList);
			if(insertBindCount != 1){
				throw new ServiceException("商户【"+beforeMchtCd+"】绑定商户关系Bind表插入失败");
			}
			
			logger.info("商户【"+beforeMchtCd+"】终端【"+beforeTermId+"】和商户【"+bindMchtCd+"】终端【"+bindTermId+"】插入绑定关系表成功");
			
			//保存商户绑定关系
			baseDao.addSyslog(SysLogType.INSERT_BIND_MER.getCode(),
					SysLogType.INSERT_BIND_MER.getName(),
					logingMerchant.getAccountNo(), 
					"操作员【"+logingMerchant.getAccountNo()+"】保存商户【"+beforeMchtCd+"】终端【"+beforeTermId+"】和商户【"+bindMchtCd+"】终端【"+bindTermId+"】绑定关系成功");
			
			logger.info("商户【"+beforeMchtCd+"】终端【"+beforeTermId+"】和商户【"+bindMchtCd+"】终端【"+bindTermId+"】建立绑定关系成功");
			
		} catch (Exception e) {
			logger.error("绑定商户关系失败",e);
			throw new ServiceException("绑定商户关系失败");
		}
		resMap.put("flag", true);
		resMap.put("msg", "操作成功");
		return resMap;
	}

}
